package com.gaoyi.websocket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gaoyi.websocket.common.ServerResponse;
import com.gaoyi.websocket.entity.WmsUser;
import com.gaoyi.websocket.mapper.WmsUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/wms")
public class WmsUserController{

    @Resource
    WmsUserMapper wmsUserMapper;

    @RequestMapping("/query")
    public ServerResponse queryUser(String username, @RequestParam(defaultValue = "1") int pageNo,
                                    @RequestParam(defaultValue = "10")int pageSize){
        List<WmsUser> wmsUsers;
        PageHelper.startPage(pageNo, pageSize);
        wmsUsers = (username == null || username == "") ? wmsUserMapper.selectList(null) :
                wmsUserMapper.selectList(new QueryWrapper<WmsUser>().like("username",username));
        PageInfo<WmsUser> pageInfo = new PageInfo<WmsUser>(wmsUsers);
        return ServerResponse.successResponse(pageInfo);
    }

    @RequestMapping("/edit")
    public ServerResponse editUser(WmsUser wmsUser){

        wmsUserMapper.updateById(wmsUser);
        return ServerResponse.success();
    }

    @RequestMapping("/add")
    @ResponseBody
    public ServerResponse addUser(@RequestBody WmsUser wmsUser) {
        String account = wmsUser.getAccount();
        String password = wmsUser.getPassword();
        if (wmsUserMapper.selectOne(new QueryWrapper<WmsUser>().eq("account",account)) != null) {
            return ServerResponse.errorMessage("账号已被注册");
        }
        // 生成盐,默认长度 16 位
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // 设置 hash 算法迭代次数
        int times = 2;
        // 得到 hash 后的密码
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        // 存储用户信息，包括 salt 与 hash 后的密码
        wmsUser.setSalt(salt);
        wmsUser.setPassword(encodedPassword);
        wmsUserMapper.insert(wmsUser);
        return ServerResponse.success();
    }

    @RequestMapping("/delete")
    public ServerResponse deleteUser(int id){
        wmsUserMapper.deleteById(id);
        return ServerResponse.success();
    }
}
